package eraserhead.xml;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Convenience class for parsing Xml
 * @author Michael Checca
 */
public class XmlNode {
	/**
	 * Finds a node with the specified name
	 * @param node Node to search
	 * @param name Name of inner node to find
	 * @return {@link Node} if it exists, false otherwise
	 */
	public static Node findNode(Node node, String name) {
		if (node.getNodeName().equals(name))
			return node;
		NodeList children = node.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			if (children.item(i).getNodeName().equals(name))
				return children.item(i);
		}
		return null;
	}

	/**
	 * Gets a node's attribute as a string
	 * @param node Node to search
	 * @param name Name of the attribute to get
	 * @return Attribute if it exists, otherwise the empty string "" is returned
	 */
	public static String getAttribute(Node node, String name) {
		Node attr = node.getAttributes().getNamedItem(name);
		if (attr != null)
			return attr.getNodeValue();
		else
			return "";
	}

	/**
	 * Gets a node's attribute as an int
	 * @param node Node to search
	 * @param name Name of attribute to get
	 * @return Attribute as an int if it exists, otherwise 0 is returned
	 */
	public static int getAttributeInt(Node node, String name) {
		try {
			return Integer.parseInt(getAttribute(node, name));
		} catch (NumberFormatException nfe) {
			return 0;
		}
	}

	/**
	 * Gets a node's attribute as a boolean
	 * @param node Node to search
	 * @param name Name of attribute to get
	 * @return Attribute as an boolean if it exists, otherwise false is returned
	 */
	public static boolean getAttributeBool(Node node, String name) {
		String bool = getAttribute(node, name).toLowerCase();
		return bool.equals("true");
	}
}
